using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using ORS.OrderRobot.Domain;
using ORS.OrderRobot.IOC;
using ORS.OrderRobot.Service.Helper;
using ORS.OrderRobot.ServiceContracts;
using ORS.OrderRobot.ServiceContracts.Dtos.Api;
using ORS.OrderRobot.ServiceContracts.ThridPartApi;

namespace ORS.OrderRobot.Service.Jobs
{
    /// <summary>
    /// 更新远程用户资料
    /// </summary>
    public class UpdateAccountProfileJob : IBackgroundJob<UpdateProfileArgs>, IScoped
    {
        private readonly ILogger<UpdateAccountProfileJob> _logger;
        private readonly IHubContext<MessageHub> _hubContext;
        private readonly IAccountLoginService _accountLoginService;
        private readonly IThirdAccountService _thridAccountService;
        private readonly IRepository<AccountBoarding, int> _accountBoardingRepository;
        public UpdateAccountProfileJob(
            ILogger<UpdateAccountProfileJob> logger,
            IAccountLoginService accountLoginService,
            IThirdAccountService thridAccountService,
            IRepository<AccountBoarding, int> accountBoardingRepository,
            IHubContext<MessageHub> hubContext)
        {
            _logger = logger;
            _accountLoginService = accountLoginService;
            _thridAccountService = thridAccountService;
            _accountBoardingRepository = accountBoardingRepository;
            _hubContext = hubContext;
        }

        public async Task ExecuteAsync(UpdateProfileArgs args)
        {
            _logger.LogInformation($"账号数据同步开始：{DateTime.Now.China()}");
            await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = args.Email, Action = $"账号数据同步开始" });
            var userLoginInfo = await _accountLoginService.GetLoginInfoAsync(args.Email);
            if (userLoginInfo == null)
            {
                userLoginInfo = await _accountLoginService.LoginAsync(args.Email, args.Password);
            }

            if (userLoginInfo == null)
            {
                await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = args.Email, Action = $"登录失败,无法更新资料", Type = Consts.ErrMsg });
                _logger.LogError("用户登录失败,无法更新资料.email:{email}", args.Email);
                return;
            }

            var updateUserInput = new UpdateUserInput
            {
                CustomerId = userLoginInfo.CustomerId,
                Token = userLoginInfo.Token,
                UserInfo = new UpdateUserInfo
                {
                    FirstName = args.First_Name,
                    LastName = args.Last_Name,
                    Birthday = args.Birthday.Replace("/","-"),
                    PhoneMobile = args.Phone_Mobile,
                    PhoneHome = args.Phone_Mobile
                }
            };
            var latestLoginUserInfo = await _thridAccountService.UpdateInfoAsync(updateUserInput);
            if (latestLoginUserInfo != null)
            {
                await _accountLoginService.UpdateLoginCacheInfoAsync(latestLoginUserInfo);
                var boardingEntity = await _accountBoardingRepository.GetAsync(args.BoardingId);
                if (boardingEntity != null)
                {
                    boardingEntity.IsSyncToServer = true;
                    boardingEntity.SyncTime = DateTime.Now.China();
                    await _accountBoardingRepository.UpdateAsync(boardingEntity);
                    await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = args.Email, Action = "账号数据已同步到购物网站" });
                    _logger.LogInformation($"账号数据同步完成：{DateTime.Now.China()}");
                }
            }

        }
    }
} 